package com.oim.core.business.manage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import com.oim.core.app.AppContext;
import com.oim.core.bean.UserData;
import com.oim.core.business.sender.FileSender;
import com.oim.core.common.AppConstant;
import com.oim.core.common.action.CallBackAction;
import com.oim.core.common.action.FileAction;
import com.oim.core.common.app.manage.Manage;
import com.oim.core.common.box.PersonalBox;
import com.oim.core.common.component.FileHttpDownload;
import com.oim.core.common.component.FileHttpUpload;
import com.oim.core.common.task.ExecuteTask;
import com.oim.core.common.util.FileNameUtil;
import com.oim.core.net.message.data.FileData;
import com.oim.core.net.message.data.chat.Content;
import com.oim.core.net.message.data.chat.Item;
import com.oim.core.net.message.data.chat.Section;
import com.oim.core.net.server.Back;
import com.only.common.result.Info;
import com.only.common.util.OnlyFileUtil;
import com.only.general.annotation.parameter.Define;
import com.only.net.data.action.DataBackAction;

/**
 * 描述：
 * 
 * @author XiaHui
 * @date 2016年1月15日 下午7:52:44
 * @version 0.0.1
 */
public class ImageManage extends Manage {

	private String fileServerAddress;
	FileHttpUpload fhu = new FileHttpUpload();
	FileHttpDownload fhd = new FileHttpDownload();

	public ImageManage(AppContext appContext) {
		super(appContext);
	}

	public void handleImage(Content content, CallBackAction<Boolean> callBackAction) {
		ExecuteTask et = new ExecuteTask() {
			@Override
			public void execute() {
				UserData user = PersonalBox.get(UserData.class);
				String userId = (null == user) ? null : user.getId();
				Map<String, String> dataMap = new HashMap<String, String>();
				dataMap.put("userId", userId);
				List<Section> sections = content.getSections();
				if (null != sections) {
					for (Section s : sections) {
						List<Item> items = s.getItems();
						if (null != items) {
							for (Item i : items) {
								if (Item.type_image.equals(i.getType())) {
									String filePath = i.getValue();
									File file = new File(filePath);
									if (file.exists()) {
										String fileName = file.getName();
										String http = fileServerAddress + "/file/upload.do";
										FileAction fileAction = new FileAction() {

											@Override
											public void progress(long speed, long size, long up, double percentage) {

											}

											@Override
											public void success(FileData fileData) {
												String s = FileNameUtil.getSuffixName(fileName);
												String id = fileData.getId();
												String value = id + "," + s;
												i.setValue(value);
												String name = id + "." + s;
												String path = AppConstant.userHome + "/" + AppConstant.app_home_path + "/" + user.getNumber() + "/image/" + name;
												OnlyFileUtil.checkOrCreateFile(path);
												File newFile = new File(path);
												try {
													FileUtils.copyFile(file, newFile);
												} catch (IOException e) {
													e.printStackTrace();
												}
											}

											@Override
											public void lost() {
												i.setValue("");
											}

										};
										fhu.upload(http, file, dataMap, fileAction);
									} else {
										i.setValue("");
									}
								}
							}
						}
					}
				}
				callBackAction.execute(true);
			}
		};
		if (null == fileServerAddress || "".equals(fileServerAddress)) {
			DataBackAction dataBackAction = new DataBackAction() {

				@Override
				public void lost() {
					callBackAction.execute(true);
				}

				@Override
				public void timeOut() {
					callBackAction.execute(true);
				}

				@Back
				public void back(Info info, @Define("fileServerUrl") String fileServerUrl) {
					fileServerAddress = fileServerUrl;
					if (info.isSuccess()) {
						appContext.add(et);
					} else {
						callBackAction.execute(true);
					}
				}
			};
			FileSender rs = this.appContext.getSender(FileSender.class);
			rs.getFileServer(dataBackAction);
		} else {
			appContext.add(et);
		}
	}

	public void handleLocalImage(Content content, CallBackAction<List<FileData>> callBackAction) {
		ExecuteTask et = new ExecuteTask() {
			@Override
			public void execute() {
				List<FileData> list = new ArrayList<FileData>();
				// UserData user = PersonalBox.get(UserData.class);
				List<Section> sections = content.getSections();
				if (null != sections) {
					for (Section s : sections) {
						List<Item> items = s.getItems();
						if (null != items) {
							for (Item i : items) {
								if (Item.type_image.equals(i.getType())) {
									String imageInfo = i.getValue();
									if (null != imageInfo && !"".equals(imageInfo)) {
										String[] array = imageInfo.split(",");
										if (array.length > 1) {
											String id = array[0];
											String extension = array[1];
											String name = id + "." + extension;
											FileData fd = new FileData();
											fd.setName(name);
											fd.setId(id);
											list.add(fd);
										}
									}
								}
							}
						}
					}
				}
				callBackAction.execute(list);
			}
		};
		appContext.add(et);
	}

	public void downloadImage(Content content, CallBackAction<List<FileData>> callBackAction) {
		List<FileData> fileList = new ArrayList<FileData>();
		ExecuteTask et = new ExecuteTask() {
			@Override
			public void execute() {
				UserData user = PersonalBox.get(UserData.class);

				List<Section> sections = content.getSections();
				if (null != sections) {
					for (Section s : sections) {
						List<Item> items = s.getItems();
						if (null != items) {
							for (Item i : items) {
								if (Item.type_image.equals(i.getType())) {
									String imageInfo = i.getValue();
									if (null != imageInfo && !"".equals(imageInfo)) {
										String[] array = imageInfo.split(",");
										if (array.length > 1) {
											String id = array[0];
											String extension = array[1];
											String name = id + "." + extension;
											String savaPath = AppConstant.userHome + "/" + AppConstant.app_home_path + "/" + user.getNumber() + "/image/";
											String fileName=savaPath+name;
											boolean exists=OnlyFileUtil.isFileExists(fileName);
											if(exists){
												FileData fd = new FileData();
												fd.setName(name);
												fd.setId(id);
												fileList.add(fd);
											}else{
												String http = fileServerAddress + "/file/download.do?id=" + id;
												FileAction fileAction = new FileAction() {

													@Override
													public void progress(long speed, long size, long up, double percentage) {

													}

													@Override
													public void success(FileData fileData) {
														FileData fd = new FileData();
														fd.setName(name);
														fd.setId(id);
														fileList.add(fd);
													}

													@Override
													public void lost() {
														FileData fd = new FileData();
														fd.setName("");
														fd.setId(id);
														fileList.add(fd);
													}

												};
												
												fhd.download(http, savaPath, id, true, fileAction);
											}
										}
									}
								}
							}
						}
					}
				}
				callBackAction.execute(fileList);
			}
		};
		if (null == fileServerAddress || "".equals(fileServerAddress)) {
			DataBackAction dataBackAction = new DataBackAction() {

				@Override
				public void lost() {
					callBackAction.execute(fileList);
				}

				@Override
				public void timeOut() {
					callBackAction.execute(fileList);
				}

				@Back
				public void back(Info info, @Define("fileServerUrl") String fileServerUrl) {
					fileServerAddress = fileServerUrl;
					if (info.isSuccess()) {
						appContext.add(et);
					} else {
						callBackAction.execute(fileList);
					}
				}
			};
			FileSender rs = this.appContext.getSender(FileSender.class);
			rs.getFileServer(dataBackAction);
		} else {
			appContext.add(et);
		}
	}
}
